const express = require('express');
const pool = require('../db/mysql');
const uid = require('../db/uid');

const router = express.Router();

router.post( '/comment/publish' , (req,resp)=>{

    let customer = req.session.customer ;
    if( customer ) {
        let tid = req.body.topicId ;
        let content = req.body.content ;

        let id = uid.idGenerator();
        let cid = customer.id ;
        let time = new Date();
        let ip = req.ip.match(/\d+\.\d+\.\d+\.\d+/);
        ip = ip == null ? ip : ip[0] ;

        let sql = `INSERT INTO t_comments 
                   ( id , content , customer_id , topic_id , comment_time , comment_ip )
                   VALUES 
                   ( ? , ? , ? , ? , ? , ? )` ;

        let params = [ id , content , cid , tid , time , ip ];
        let handler = (error,results,fields) =>{
            if( error ) {
                throw error ;
            }
            resp.redirect( `/topic/detail/${tid}` );
        }
        pool.execute( sql , params , handler );

        return ;
    }
    resp.redirect( '/customer/sign/in' );
});

module.exports = router ;